<template>
  <el-dialog v-if="visible" v-model="visible" :close-on-click-modal="false" :show-close="false"
             :close-on-press-escape="false" width="500px">
    <div class="detailDialog">{{ accountData.form.employeeId ? '编辑账号' : '新增账号'}}</div>
    <el-form class="form" ref="formRef" :model="accountData.form" label-width="80px" :status-icon="true"
             :show-message="false">
      <el-form-item label="账号" prop="employeeAccount" required>
        <el-input class="boss_input" v-model="accountData.form.employeeAccount" placeholder="请输入账号"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" :rules="{ required: !accountData.form.employeeId, validator: validateNewPassword, trigger: 'blur' }">
        <el-input class="boss_input" type="password" v-model="accountData.form.password"
                  :placeholder="accountData.form.employeeId ? '不填则不修改' : '长度应为8~15个字符,必须包含大写,小写字母和数字'" clearable></el-input>
      </el-form-item>
      <el-form-item label="名称" prop="employeeName" required>
        <el-input class="boss_input" v-model="accountData.form.employeeName" placeholder="请输入姓名"
                  clearable></el-input>
      </el-form-item>
      <el-form-item label="手机号">
        <el-input class="boss_input" v-model="accountData.form.employeePhone" placeholder="请输入手机号"
                  clearable></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <Button label="关闭" @click="onCancelClick" />
      <Button label="确认" type="primary" @click="onSubmitClick" />
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, computed, watch, onMounted, nextTick } from 'vue'
import api from '@/api'
import Button from '@/components/button/button.vue'

const emit = defineEmits(['update:visible', 'change'])
const props = defineProps(['visible', 'form'])

const formRef = ref()

watch(
  () => props.form,
  (val) => {
    if (val) {
      accountData.form = val
    }
  }
)

const accountData = reactive({
  form: {}
})

const visible = computed({
  get: () => {
    return props.visible
  },
  set: (value) => emit('update:visible', value)
})

const onCancelClick = () => {
  visible.value = false
}

const validateNewPassword = (rule, value, callback) => {
  const reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,15}$/
  // 非必填且值为空时直接通过
  if (!rule.required && !value) {
    return callback()
  }
  // 验证密码
  if (!reg.test(value)) {
    callback(new Error('长度应为8~15个字符,必须包含大写,小写字母和数字'))
  } else {
    callback()
  }
}

const onSubmitClick = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      emit('change', accountData.form)
      visible.value = false
    }
  })
}
</script>
<style scoped>
.detailDialog {
  font-size: 18px;
  color: #303133;
  font-weight: 600;
  margin-bottom: 20px;
}

</style>
